package com.bingo.filter;

import lombok.Getter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        String auth = queryParams.getFirst("auth");
        if ("admin".equals(auth)) {
            return chain.filter(exchange);
        }
        return Mono.error(new BizException(404, "无权限啦"));
    }


    public int getOrder() {
        return -1;
    }

    @Getter
    public static class BizException extends RuntimeException {

        public static final int FINAL_CODE = 500;
        protected int code;
        protected String message;

        public BizException() {
        }

        public BizException(String message) {
            super(message);
            this.message = message;
            this.code = 500;
        }

        public BizException(int code, String message) {
            super(message);
            this.message = message;
            this.code = code;
        }

    }
}